package org.study.data.migration.boot.service.impl;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.study.data.migration.boot.mapper.DataMapper;
import org.study.data.migration.boot.service.DataService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 数据处理接口实现类
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年03月04日
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DataServiceImpl implements DataService {
    private final DataMapper dataMapper;

    @Override
    public boolean dataMigration(String sourceTableName, String targetTableName) {
        List<Map<String, Object>> dataList = dataMapper.selectDataFromSource(sourceTableName);
        log.info("查询到的数据条数：{}", dataList.size());
        if (CollectionUtils.isNotEmpty(dataList)) {
            // 找出元素最多的map
            Map<String, Object> maxDataMap = dataList.stream().max(Comparator.comparingInt(Map::size)).orElse(null);
            // 遍历，补全数据，因为值为null的列不会出现在上面的map中
            for (Map<String, Object> objectMap : dataList) {
                if (maxDataMap.size() != objectMap.size()) {
                    maxDataMap.keySet().forEach(key -> objectMap.put(key, objectMap.get(key)));
                }
            }
            // dataList.forEach(data -> dataMapper.insertDataIntoTarget2(targetTableName, data));
            List<TreeMap<String, Object>> mapList = dataList.stream()
                    .map(TreeMap::new)
                    .collect(Collectors.toList());
            List<List<TreeMap<String, Object>>> split = CollUtil.split(mapList, 10);
            for (int i = 0; i < split.size(); i++) {
                int insertNum = dataMapper.insertDataIntoTarget2(targetTableName, split.get(i));
                log.info("插入批次：{}，数据条数：{}", i, insertNum);
            }
        }
        return true;
    }
}
